package com.univrz.flexmachine.scmxml
{
	
	
	import com.univrz.flexmachine.core.Node;
	import com.univrz.flexmachine.events.StateMachineEvent;
	
	
	
	
	/**
	 * 
	 * TODO: should triggers be associated to a given sm?
	 * or are they a standalone utility
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */	
	public class Trigger extends Node
	{
		
		
		[Bindable("willHaveEffectChanged")]
		public function get willHaveEffect():Boolean
		{
			for each ( var transition:Transition in transitions ) // optimization: we only loop to the first enabled
				if ( transition.isEnabled )
					return true;
			return false;
		}
	
		
		private var transitions:Array = [];
		
		
		internal function registerTransition( transition:Transition ):void
		{
			transitions.push( transition );
			transition.addEventListener( StateMachineEvent.IS_ENABLED_CHANGED, onTransitionEnabledChanged );
			update();			
		}
		
		
		private function onTransitionEnabledChanged( event:StateMachineEvent ):void
		{
			update( );
		}
		
		
		private function update( ):void
		{
			dispatchEvent( new StateMachineEvent( StateMachineEvent.WILL_HAVE_EFFECT_CHANGED ) );			
		}
		
		
		public function getEnabledTransitions():Array
		{
			var enabled:Array = [];
			for each ( var transition:Transition in transitions )
				if ( transition.isEnabled )
					enabled.push( transition );
					
			return enabled;
		}
		
	
		/**
		 * 
		 * Will trigger this trigger...
		 * 
		 */		
		public function trigger( ):void
		{
		
			for each ( var transition:Transition in getEnabledTransitions() )
			{
				transition.fire( );
			}
		
		}
		
	}
	
}